/*
 * JFInicio.java
 *
 * Created on 25/07/2011, 20:24:58
 */
package Frames;

import java.awt.Desktop;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import mercado.ab.CxVenda;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;

public class JFInicio extends javax.swing.JFrame {

    String nivelFunc;
    String userFunc;

    public JFInicio(String nivel, String user) {
        this.nivelFunc = nivel; // Variaveis servirao para logar ocorrencias e para habilitar ou nao alguns menus
        this.userFunc = user;


        this.setIconImage(new ImageIcon("cheff_256.png").getImage());
        initComponents();
        menuFuncionario.setMnemonic('F');
        menuArquivo.setMnemonic('A');
        menuCliente.setMnemonic('C');
        menuEmpresa.setMnemonic('E');
        menuRelatorio.setMnemonic('R');
        menuProduto.setMnemonic('P');

        validarNivel(nivel);

        this.setLocationRelativeTo(null);
        this.setResizable(false);

    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        painel = new javax.swing.JPanel();
        barraDeMenu = new javax.swing.JMenuBar();
        menuArquivo = new javax.swing.JMenu();
        menuItemInicio = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        menuItemLoggof = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();
        menuItemSair = new javax.swing.JMenuItem();
        menuVenda = new javax.swing.JMenu();
        menuCliente = new javax.swing.JMenu();
        menuFuncionario = new javax.swing.JMenu();
        menuProduto = new javax.swing.JMenu();
        menuEmpresa = new javax.swing.JMenu();
        menuRelatorio = new javax.swing.JMenu();
        mnItemRelatorioProdutos = new javax.swing.JMenuItem();
        mnItemRelatorioFuncAtivos = new javax.swing.JMenuItem();
        menuAjuda = new javax.swing.JMenu();
        menuItemAjuda = new javax.swing.JMenuItem();
        menuItemSobre = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout painelLayout = new javax.swing.GroupLayout(painel);
        painel.setLayout(painelLayout);
        painelLayout.setHorizontalGroup(
            painelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 763, Short.MAX_VALUE)
        );
        painelLayout.setVerticalGroup(
            painelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 516, Short.MAX_VALUE)
        );

        barraDeMenu.setEnabled(false);

        menuArquivo.setText("Arquivo");

        menuItemInicio.setText("Início");
        menuItemInicio.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemInicioActionPerformed(evt);
            }
        });
        menuArquivo.add(menuItemInicio);

        jMenuItem2.setText("Alterar Senha");
        menuArquivo.add(jMenuItem2);

        menuItemLoggof.setText("Trocar Usuário");
        menuItemLoggof.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemLoggofActionPerformed(evt);
            }
        });
        menuArquivo.add(menuItemLoggof);

        jMenuItem1.setText("Opções");
        menuArquivo.add(jMenuItem1);

        menuItemSair.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_W, java.awt.event.InputEvent.CTRL_MASK));
        menuItemSair.setText("Sair");
        menuItemSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemSairActionPerformed(evt);
            }
        });
        menuArquivo.add(menuItemSair);

        barraDeMenu.add(menuArquivo);

        menuVenda.setText("Venda");
        menuVenda.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                menuVendaMouseClicked(evt);
            }
        });
        barraDeMenu.add(menuVenda);

        menuCliente.setText("Cliente");
        menuCliente.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                menuClienteMouseClicked(evt);
            }
        });
        barraDeMenu.add(menuCliente);

        menuFuncionario.setText("Funcionário");
        menuFuncionario.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                menuFuncionarioMouseClicked(evt);
            }
        });
        barraDeMenu.add(menuFuncionario);

        menuProduto.setText("Produto");
        menuProduto.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                menuProdutoMouseClicked(evt);
            }
        });
        barraDeMenu.add(menuProduto);

        menuEmpresa.setText("Empresa");
        menuEmpresa.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                menuEmpresaMouseClicked(evt);
            }
        });
        barraDeMenu.add(menuEmpresa);

        menuRelatorio.setText("Relatório");

        mnItemRelatorioProdutos.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK));
        mnItemRelatorioProdutos.setText("Produtos");
        mnItemRelatorioProdutos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnItemRelatorioProdutosActionPerformed(evt);
            }
        });
        menuRelatorio.add(mnItemRelatorioProdutos);

        mnItemRelatorioFuncAtivos.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        mnItemRelatorioFuncAtivos.setText("Empresas Conveniadas");
        mnItemRelatorioFuncAtivos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnItemRelatorioFuncAtivosActionPerformed(evt);
            }
        });
        menuRelatorio.add(mnItemRelatorioFuncAtivos);

        barraDeMenu.add(menuRelatorio);

        menuAjuda.setText("Ajuda");

        menuItemAjuda.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F11, java.awt.event.InputEvent.CTRL_MASK));
        menuItemAjuda.setText("Conteúdo da Ajuda");
        menuItemAjuda.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemAjudaActionPerformed(evt);
            }
        });
        menuAjuda.add(menuItemAjuda);

        menuItemSobre.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F12, java.awt.event.InputEvent.CTRL_MASK));
        menuItemSobre.setText("Sobre");
        menuItemSobre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemSobreActionPerformed(evt);
            }
        });
        menuAjuda.add(menuItemSobre);

        barraDeMenu.add(menuAjuda);

        setJMenuBar(barraDeMenu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(painel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(painel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void menuEmpresaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuEmpresaMouseClicked
    if (menuEmpresa.isEnabled()) {
        Tela_Empresa tela = new Tela_Empresa();
        painel.removeAll();
        painel.add(tela.getLayeredPane());
        painel.repaint();
    }
}//GEN-LAST:event_menuEmpresaMouseClicked

private void menuClienteMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuClienteMouseClicked
    if (menuCliente.isEnabled()) {

        Tela_Cliente telaCliente = new Tela_Cliente();

        painel.removeAll();
        painel.add(telaCliente.getLayeredPane());
        painel.repaint();
    }
}//GEN-LAST:event_menuClienteMouseClicked

private void menuProdutoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuProdutoMouseClicked
    if (menuProduto.isEnabled()) {
        Tela_Produto tela = new Tela_Produto();
        painel.removeAll();
        painel.add(tela.getLayeredPane());
        painel.repaint();
    }
}//GEN-LAST:event_menuProdutoMouseClicked

private void menuFuncionarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuFuncionarioMouseClicked
    if (menuFuncionario.isEnabled()) {
        Tela_Funcionario tela = new Tela_Funcionario();
        painel.removeAll();
        painel.add(tela.getLayeredPane());
        painel.repaint();
    }
}//GEN-LAST:event_menuFuncionarioMouseClicked

private void mnItemRelatorioProdutosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnItemRelatorioProdutosActionPerformed
    JOptionPane.showMessageDialog(this, "Relatório Estoque");
    try {
        gerarRelatorioProduto();
    } catch (NumberFormatException e) {
        e.printStackTrace();
    } catch (JRException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}//GEN-LAST:event_mnItemRelatorioProdutosActionPerformed

private void menuItemSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemSairActionPerformed
    System.exit(0);
}//GEN-LAST:event_menuItemSairActionPerformed

private void menuItemInicioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemInicioActionPerformed
    painel.removeAll();
    painel.repaint();// TODO add your handling code here:
}//GEN-LAST:event_menuItemInicioActionPerformed

private void menuItemLoggofActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemLoggofActionPerformed

    int resp = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja trocar de usuário?", "Trocar Usuário", NORMAL);
    if (resp == 0) {
        JFLogin login = new JFLogin();
        login.setVisible(true);

        this.dispose();
    }



}//GEN-LAST:event_menuItemLoggofActionPerformed

private void menuVendaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_menuVendaMouseClicked
    if (menuVenda.isEnabled()) {
        CxVenda tela = new CxVenda();
        painel.removeAll();
        painel.add(tela.getLayeredPane());
        painel.repaint();
    }
}//GEN-LAST:event_menuVendaMouseClicked

private void menuItemSobreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemSobreActionPerformed
    JFSobre tela = new JFSobre();
    painel.removeAll();
    painel.add(tela.getLayeredPane());
    painel.repaint();
}//GEN-LAST:event_menuItemSobreActionPerformed

private void menuItemAjudaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemAjudaActionPerformed
    Desktop desktop = Desktop.getDesktop();
    try {
        desktop.open(new File("MANUAL PROJETO.pdf"));
    } catch (IOException ex) {
        System.out.println("File Error");
    }
}//GEN-LAST:event_menuItemAjudaActionPerformed

private void mnItemRelatorioFuncAtivosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnItemRelatorioFuncAtivosActionPerformed
    try {
        gerarRelatorioEmpresaConv();
    } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JRException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }// TODO add your handling code here:
}//GEN-LAST:event_mnItemRelatorioFuncAtivosActionPerformed
    /**
     * @param args the command line arguments
     */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuBar barraDeMenu;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenu menuAjuda;
    private javax.swing.JMenu menuArquivo;
    private javax.swing.JMenu menuCliente;
    private javax.swing.JMenu menuEmpresa;
    private javax.swing.JMenu menuFuncionario;
    private javax.swing.JMenuItem menuItemAjuda;
    private javax.swing.JMenuItem menuItemInicio;
    private javax.swing.JMenuItem menuItemLoggof;
    private javax.swing.JMenuItem menuItemSair;
    private javax.swing.JMenuItem menuItemSobre;
    private javax.swing.JMenu menuProduto;
    private javax.swing.JMenu menuRelatorio;
    private javax.swing.JMenu menuVenda;
    private javax.swing.JMenuItem mnItemRelatorioFuncAtivos;
    private javax.swing.JMenuItem mnItemRelatorioProdutos;
    private javax.swing.JPanel painel;
    // End of variables declaration//GEN-END:variables

    public void gerarRelatorioEmpresaConv() throws JRException, SQLException,
            ClassNotFoundException {
        // gerando o jasper design

        String layout = "C:/Users/Monitor/Documents/NetBeansProjects/src/Frames//relatorioEmpresaConv.jrxml";

        JasperDesign desenho = JRXmlLoader.load(layout);

        // compila o relatório
        JasperReport relatorio = JasperCompileManager.compileReport(desenho);

        // estabelece conexão
        Class.forName("org.postgresql.Driver");
        Connection con = DriverManager.getConnection("jdbc:postgresql://10.0.30.18:5432/postgres", "postgres", "postgres");
        Statement stm = (Statement) con.createStatement();
        //Statement stmAux = con.createStatement();
        String query = "select * from empresa";
        //String queryAux = "";

        //query = "select * from che_cheque, ban_banco, fun_funcionario where ban_cod_banco = che_ban_cheque and fun_cpf_funcionario = che_rec_cheque";
        // queryAux = "select * from che_cheque, ban_banco, fun_funcionario where ban_cod_banco = che_ban_cheque and fun_cpf_funcionario = che_rec_cheque";


        ResultSet rs = stm.executeQuery(query);
        //ResultSet rsAux = stmAux.executeQuery(queryAux);
        //Long soma = 0L;
        // while (rsAux.next()) {
        //  soma = soma + new Long(rsAux.getString("che_val_cheque"));
        //  }

        // implementação da interface JRDataSource para DataSource ResultSet
        JRResultSetDataSource jrRS = new JRResultSetDataSource(rs);

        // executa o relatório
        Map parametros = new HashMap();

        //String valor = "";
        //while(rsAux.next()){
        //    valor = rsAux.getString("valorTotal");
        //}

        parametros.put("param1", null);

        JasperPrint impressao = JasperFillManager.fillReport(relatorio,
                parametros, jrRS);

        // exibe o resultado
        JasperViewer viewer = new JasperViewer(impressao, false);
        con.close();
        viewer.show();
    }

    public void gerarRelatorioProduto() throws JRException, SQLException,
            ClassNotFoundException {
        // gerando o jasper design

        String layout = "C:/Users/Monitor/Documents/NetBeansProjects/src/Frames/relatorioProduto.jrxml";

        JasperDesign desenho = JRXmlLoader.load(layout);

        // compila o relatório
        JasperReport relatorio = JasperCompileManager.compileReport(desenho);

        // estabelece conexão
        Class.forName("org.postgresql.Driver");
        Connection con = DriverManager.getConnection("jdbc:postgresql://10.0.30.18:5432/postgres", "postgres", "postgres");
        Statement stm = (Statement) con.createStatement();
        //Statement stmAux = con.createStatement();
        String query = "select * from produto";
        //String queryAux = "";

        //query = "select * from che_cheque, ban_banco, fun_funcionario where ban_cod_banco = che_ban_cheque and fun_cpf_funcionario = che_rec_cheque";
        // queryAux = "select * from che_cheque, ban_banco, fun_funcionario where ban_cod_banco = che_ban_cheque and fun_cpf_funcionario = che_rec_cheque";


        ResultSet rs = stm.executeQuery(query);
        //ResultSet rsAux = stmAux.executeQuery(queryAux);
        //Long soma = 0L;
        // while (rsAux.next()) {
        //  soma = soma + new Long(rsAux.getString("che_val_cheque"));
        //  }

        // implementação da interface JRDataSource para DataSource ResultSet
        JRResultSetDataSource jrRS = new JRResultSetDataSource(rs);

        // executa o relatório
        Map parametros = new HashMap();

        //String valor = "";
        //while(rsAux.next()){
        //    valor = rsAux.getString("valorTotal");
        //}

        parametros.put("param1", null);

        JasperPrint impressao = JasperFillManager.fillReport(relatorio,
                parametros, jrRS);

        // exibe o resultado
        JasperViewer viewer = new JasperViewer(impressao, false);
        con.close();
        viewer.show();
    }

    private void validarNivel(String nivel) {
        if (nivel.equals("Gerente")) {

            menuArquivo.setEnabled(true);
            menuVenda.setEnabled(true);
            menuCliente.setEnabled(true);
            menuFuncionario.setEnabled(true);
            menuProduto.setEnabled(true);
            menuEmpresa.setEnabled(true);
            menuRelatorio.setEnabled(true);
            menuAjuda.setEnabled(true);


        } else if(nivel.equals("Atendente")) {
            menuProduto.setEnabled(false);
            menuAjuda.setEnabled(true);
            menuArquivo.setEnabled(true);
            menuVenda.setEnabled(true);
            menuCliente.setEnabled(false);
            menuFuncionario.setEnabled(false);
            menuRelatorio.setEnabled(false);
            menuEmpresa.setEnabled(false);
        }else{
            menuProduto.setEnabled(false);
            menuAjuda.setEnabled(true);
            menuArquivo.setEnabled(true);
            menuVenda.setEnabled(false);
            menuCliente.setEnabled(false);
            menuFuncionario.setEnabled(false);
            menuRelatorio.setEnabled(false);
            menuEmpresa.setEnabled(false);
        }
    }
}
